package com.example.charactivity.ChartWeekly

import android.app.usage.UsageStatsManager
import android.os.Build
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ScrollView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.charactivity.ChartDaily.DayChartViewModel
import com.example.charactivity.GernerChartModel
import com.example.charactivity.UsageStatics
import com.example.recyclerview.viewHolder.ViewAdapter
import com.example.remindme.R
import com.github.aachartmodel.aainfographics.aachartcreator.AAChartView
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
import kotlin.concurrent.thread

class WeeklyFragment : Fragment() {

    companion object {
        fun newInstance() = WeeklyFragment()
    }
    private val usageStatics by lazy {
        UsageStatics()
    }
    private val myChartModel by lazy {
        GernerChartModel()
    }

    private lateinit var   aaChartView: AAChartView

    private lateinit var viewModel: WeeklyViewModel
    lateinit var lastBtn:Button
    lateinit var nextBtn:Button
    lateinit var now:Calendar

    lateinit var weekRecycler: RecyclerView
    lateinit var getTop:Button
    lateinit var weekScrollView: ScrollView


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.weekly_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this).get(WeeklyViewModel::class.java)
        // 初始化的时候，现在的时间都是默认为当前的时间
         now=Calendar.getInstance()
        // 一开始的curren都是比他小的才对
        viewModel.currntTime= Calendar.getInstance()
        val v=getView()
        if(v!=null)
        {
            aaChartView = v.findViewById(R.id.week_chart_view)
            lastBtn=v.findViewById(R.id.lastw)
            nextBtn=v.findViewById(R.id.nextw)
            weekRecycler=v.findViewById(R.id.weekrecycler)
            getTop=v.findViewById(R.id.gotop)
            weekScrollView=v.findViewById(R.id.weekScro)
        //   dayRecycler=v.findViewById<RecyclerView>(R.id.recyclerview)
        }
        aaChartView.aa_drawChartWithChartModel(GernerChartModel.aaChartModel)
        viewModel.changeMaker.observe(this,{
            WeeklyViewModel.configureChart()
            aaChartView.aa_drawChartWithChartModel(GernerChartModel.aaChartModel)
            // 逻辑：按钮点击，通过getinformation 多线程调取后台数据
            // viewModel检测到数据变化，开始画图
        }
        )
        nextBtn.isEnabled=false
        weekRecycler.layoutManager= LinearLayoutManager(activity)

        // 更新信息以后，再去更新ui
        configurRecycler()
        initButton()
        getInformation()

       // dayRecycler.layoutManager= LinearLayoutManager(activity)
    // 加载生存于本fragment的recycler

    // 当前周
    }

    private fun configurRecycler() {
        val adapter= ViewAdapter(WeeklyViewModel.appinfo)  // adapeter 会在内部完成
        weekRecycler.adapter=adapter
    }

    private fun initButton() {
        nextBtn.isEnabled=false
        lastBtn.setOnClickListener{
            weekScrollView.smoothScrollTo(0,0)
            viewModel.currntTime.add(Calendar.DAY_OF_YEAR,-7)
            getInformation()
            configurRecycler()
            nextBtn.isEnabled = viewModel.currntTime < now
        }
        nextBtn.setOnClickListener{
// 两个按钮的点击事件，分别对应获取前一天和下一天的信息。但是要判断一下是否已经超过了
            weekScrollView.smoothScrollTo(0,0)
            viewModel.currntTime.add(Calendar.DAY_OF_YEAR,7)
            getInformation()
            configurRecycler()
            nextBtn.isEnabled = viewModel.currntTime < now
        }

    }


    fun getInformation() {  // 默认查询本周
        val cycleLength=1000*60*60*24*7
        val endTime = viewModel.currntTime.timeInMillis   //结束时间
        //  val beginTime = endTime - 1000 * 60 * 60 * 24 * 1 //最近3天
        val beginTime=endTime-cycleLength
// 得到一周的毫秒数了
        val format: DateFormat = SimpleDateFormat("yyyy.MM.dd", Locale.getDefault())
        val beginStr:String=format.format(Date(beginTime))
        val endStr:String=format.format(Date(endTime))
        // 修改标题
        GernerChartModel.aaChartModel.title("$beginStr—$endStr")

// 在frgment里面利用activity获取当前的activity
        val usageStateManager= activity!!.getSystemService(AppCompatActivity.USAGE_STATS_SERVICE) as UsageStatsManager
        val usageStatsList =usageStateManager .queryUsageStats(UsageStatsManager.INTERVAL_WEEKLY, beginTime, endTime)
        thread {
            viewModel.changeMaker.postValue(viewModel.sortData(usageStatsList))
        }
    }

}